import logging

from django.core.paginator import Paginator
from django.db import DatabaseError
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render

from carsearch.models import Record


def search(request):
    """查询"""
    context = {
        'searched': False,
        'current_page': 1,
        'total_page': 0
    }
    if request.method == 'POST':
        carno = request.POST.get('carno', '')
        carno = carno.replace(' ', '').upper()
        context['carno'] = carno
        page = int(request.POST.get('page', '1'))
        size = int(request.POST.get('size', '5'))
        if carno:
            context['searched'] = True
            queryset = Record.objects.filter(
                Q(car__carno__startswith=carno) |
                Q(car__owner__contains=carno)
            ).select_related('car').order_by('-offend_time')
            paginator = Paginator(queryset, size)
            context['total_page'] = paginator.num_pages
            context['page_obj'] = paginator.get_page(page)
    return render(request, 'index.html', context)


def handle(request):
    """受理违章记录"""
    data = {'code': 101, 'message': '受理失败'}
    rno = int(request.GET.get('rno', '0'))
    try:
        record = Record.objects.filter(no=rno).first()
        if record:
            if not record.dealed:
                record.dealed = True
                record.save()
            data = {'code': 100, 'message': '受理成功'}
    except DatabaseError as err:
        logging.error(str(err))
    return JsonResponse(data)
